﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq.Extensions;
using Abp.UI;
using SingleUserMall.Common;
using SingleUserMall.Items.Form;
using SingleUserMall.Items.VO;
using SingleUserMall.Stores;
using SingleUserMall.StoreSettings;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Runtime.Session;
using SingleUserMall.Dividends;
using static SingleUserMall.Items.Item;

namespace SingleUserMall.Items
{
    [AbpAuthorize]
    public class ItemManageAppService : SingleUserMallAppServiceBase, IItemManageAppService
    {
        private readonly IRepository<Item, long> _itemRepository;
        private readonly IRepository<ItemComment, long> _itemCommentRepository;
        private readonly IRepository<ItemSpec, long> _itemSpecRepository;
        private readonly IRepository<ItemCategory, long> _itemCategoryRepository;
        private readonly IRepository<RecommendCategory, long> _recommendCategoryRepository;
        private readonly IRepository<Dividend, long> _dividendRepository;
        private readonly IRepository<Store> _storeRepository;
        private readonly IRepository<ItemSkuCategory, long> _itemSkuCategoryRepository;
        private readonly IRepository<ItemSku, long> _itemSkuRepository;
        private readonly IRepository<BusinessScope, long> _businessScopeRepository;
        private readonly IRepository<StoreSetting, long> _storeSettingRepository;
        public ItemManageAppService(
            IRepository<Item, long> itemRepository,
            IRepository<ItemComment, long> itemCommentRepository,
            IRepository<ItemSpec, long> itemSpecRepository,
            IRepository<ItemCategory, long> itemCategoryRepository,
            IRepository<RecommendCategory, long> recommendCategoryRepository,
            IRepository<Dividend, long> dividendRepository,
            IRepository<Store> storeRepository,
            IRepository<ItemSkuCategory, long> itemSkuCategoryRepository,
            IRepository<ItemSku, long> itemSkuRepository,
            IRepository<BusinessScope, long> businessScopeRepository,
           IRepository<StoreSetting, long> storeSettingRepository
            )
        {
            _itemRepository = itemRepository;
            _itemCommentRepository = itemCommentRepository;
            _itemSpecRepository = itemSpecRepository;
            _itemCategoryRepository = itemCategoryRepository;
            _recommendCategoryRepository = recommendCategoryRepository;
            _dividendRepository = dividendRepository;
            _storeRepository = storeRepository;
            _itemSkuCategoryRepository = itemSkuCategoryRepository;
            _itemSkuRepository = itemSkuRepository;
            _businessScopeRepository = businessScopeRepository;
            _storeSettingRepository = storeSettingRepository;
        }

       

        public async Task<ItemVO> GetItemAsync(SingleId<long> form)
        {
            var item = await _itemRepository.FirstOrDefaultAsync(form.Id);
            return item.ToVO<Item, ItemVO>();
        }

        public async Task<ListResultDto<ItemCategoryVO>> GetItemCategoriesAsync(ItemCategorySearchForm form)
        {
            var categories = _itemCategoryRepository.GetAll()
                .Where(x => x.StoreId == form.StoreId)
                .WhereIf(form.ItemCategoryId.HasValue, x => x.ParentId == form.ItemCategoryId)
                .WhereIf(!form.ItemCategoryId.HasValue, x => x.ParentId == null)
                .OrderBy(x => x.Sort).ThenByDescending(x => x.CreationTime);
            return await categories.ToListResultDtoAsync<ItemCategory, ItemCategoryVO>((i, vo) =>
            {
                vo.SubItemCategories = _itemCategoryRepository.GetAll()
                .Where(x => x.ParentId == i.Id).ToList().ToListVO<ItemCategory, SubItemCategoryVO>();
            });
        }

        public async Task<PagedResultDto<ItemCommentVO>> GetItemCommentsAsync(ItemCommentSearchForm form)
        {
            var comments = _itemCommentRepository.GetAll().Where(x => x.ItemId == form.ItemId)
                .WhereIf(form.Star.HasValue, x => x.Star == form.Star)
                .WhereIf(form.BeginDate.HasValue, x => DbFunctions.TruncateTime(x.CreationTime) >= DbFunctions.TruncateTime(form.BeginDate))
                .WhereIf(form.EndDate.HasValue, x => DbFunctions.TruncateTime(x.CreationTime) <= DbFunctions.TruncateTime(form.EndDate))
                .OrderByDescending(x => x.CreationTime);
            return await comments.ToPagedResultDtoAsync<ItemComment, ItemCommentVO>(form, (c, vo) =>
            {
                vo.inUser = c.User;
            });
        }

        public async Task SetItemCommentReplyAsync(ItemCommentReplyForm form)
        {
            var comment = _itemCommentRepository.FirstOrDefault(form.Id);
            comment.ReplyComment = form.ReplyComment;
            comment.HasReply = true;
        }

        public async Task<PagedResultDto<ItemVO>> GetItemsAsync(ManageItemSearchForm form)
        {
            var itemCategoryIds = new List<long>();
            if (form.ItemCategoryId.HasValue)
            {
                itemCategoryIds.Add(form.ItemCategoryId.Value);
                var itemCategories = await _itemCategoryRepository.GetAllListAsync(x => x.ParentId == form.ItemCategoryId);
                itemCategories.ForEach(x =>
                {
                    itemCategoryIds.Add(x.Id);
                });
            }

            var query = _itemRepository.GetAll()
                .WhereIf(form.StoreId.HasValue, x => x.StoreId == form.StoreId)
                .WhereIf(!string.IsNullOrEmpty(form.Keywords),
                    x => x.Name.Contains(form.Keywords) || x.Tags.Contains(form.Keywords))
                .WhereIf(itemCategoryIds.Count > 0, x => itemCategoryIds.Contains(x.ItemCategoryId))
                .WhereIf(form.RecommendCategoryId.HasValue, x => x.RecommendCategoryId == form.RecommendCategoryId)
                .WhereIf(form.IsSale.HasValue, x => x.IsSale == form.IsSale)
                .WhereIf(form.IsReleasePoints.HasValue, x=> x.IsReleasePoints == form.IsReleasePoints)
                .WhereIf(form.IsHot.HasValue, x => x.IsHot == form.IsHot)
                .WhereIf(form.IsTimeLimit.HasValue, x => x.IsTimeLimit == form.IsTimeLimit)
                .WhereIf(form.IsGroup.HasValue, x => x.IsGroup == form.IsGroup)
                .WhereIf(form.IsWholesale.HasValue, x => x.IsWholesale == form.IsWholesale)
                .OrderByDescending(x => x.IsPop)
                .ThenByDescending(x => x.IsHot)
                .ThenByDescending(x => x.CreationTime);

            return await query.ToPagedResultDtoAsync<Item, ItemVO>(form, (item, vo) =>
            {
                vo.inItemCategory = item.ItemCategory;
                vo.inRecommendCategory = item.RecommendCategoryId.HasValue ? _recommendCategoryRepository.FirstOrDefault(item.RecommendCategoryId.Value) : null;
            });
        }


        public async Task<ListResultDto<ItemSkuCategoryVO>> GetItemSkusAsync(SingleId<long> form)
        {
            var itemSkuCategories = _itemSkuCategoryRepository.GetAll()
                .Where(x => x.ItemId == form.Id)
                .OrderBy(x => x.Id);
            return await itemSkuCategories.ToListResultDtoAsync<ItemSkuCategory, ItemSkuCategoryVO>((i, vo) =>
            {
                vo.ItemSkus = i.ItemSkus.OrderBy(x => x.Id).ToList().ToListVO<ItemSku, ItemSkuVO>();
            });
        }
        public async Task SetItemIsPop(SingleId<long> form)
        {
            var userId = AbpSession.GetUserId();
            bool isAdmin = await UserManager.CheckAdminAndPlatformRole(userId);
            if (!isAdmin)
            {
                throw new UserFriendlyException("您不是超级管理员 无权限操作");
            }
            var item = _itemRepository.FirstOrDefault(form.Id);
            var count = _itemRepository.Count(x => x.IsPop);
            var maxCount = _storeSettingRepository.FirstOrDefault(x => x.Id == 2).Value;
            if (maxCount > count)
            {
                item.IsPop = true;
            }
            else
            {
                throw new UserFriendlyException($"已设定超过{maxCount}件置顶商品");
            }
        }

        public async Task SetItemIsNotPop(SingleId<long> form)
        {
            var userId = AbpSession.GetUserId();
            bool isAdmin = await UserManager.CheckAdminAndPlatformRole(userId);
            if (!isAdmin)
            {
                throw new UserFriendlyException("您不是超级管理员 无权限操作");
            }
            var item = _itemRepository.FirstOrDefault(form.Id);
            item.IsPop = false;
        }

        public async Task<ListResultDto<ItemSpecManageVO>> GetItemSkuSpecsAsync(SingleId<long> form)
        {
            var skuCategories = await _itemSkuCategoryRepository.GetAll()
                .Where(x => x.ItemId == form.Id)
                .OrderBy(x => x.Id)
                .ToListAsync();
            List<List<ItemSku>> arrayItemSkus = new List<List<ItemSku>>();
            for (var i = 0; i < skuCategories.Count; i++)
            {
                var skuCategory = skuCategories[i];
                var itemSkus = await _itemSkuRepository.GetAll()
                    .Where(x => x.ItemSkuCategoryId == skuCategory.Id)
                    .OrderBy(x => x.Id)
                    .ToListAsync();
                var tempList = arrayItemSkus.Where(x => x.Count == i).ToList();
                itemSkus.ForEach(x =>
                {
                    if (i == 0)
                    {
                        arrayItemSkus.Add(new List<ItemSku> { new ItemSku {
                            Id = x.Id,
                            Sku = $"{skuCategory.Name}:{x.Sku}"
                        } });
                    }
                    else
                    {
                        tempList.ForEach(t =>
                        {
                            var list = new List<ItemSku>();
                            t.ForEach(l =>
                            {
                                list.Add(l);
                            });
                            list.Add(new ItemSku
                            {
                                Id = x.Id,
                                Sku = $"{skuCategory.Name}:{x.Sku}"
                            });
                            arrayItemSkus.Add(list);
                        });
                    }
                });
            }
            var specs = arrayItemSkus.Where(x => x.Count == arrayItemSkus.Max(a => a.Count)).Select(x =>
            {
                var specNo = string.Join("-", x.Select(t => t.Id.ToString()));
                var spec = string.Join(";", x.Select(t => t.Sku));
                var enable = _itemSpecRepository.Count(i => i.ItemId == form.Id && i.SpecNo == specNo) == 0;
                return new ItemSpecManageVO
                {
                    SpecNo = specNo,
                    Spec = spec,
                    Enabled = enable
                };
            }).ToList();
            return new ListResultDto<ItemSpecManageVO> { Items = specs };
        }

        private void RefreshSpecs(long itemId)
        {
            var specs = _itemSpecRepository.GetAll().Where(x => x.ItemId == itemId).ToList();
            specs.ForEach(spec =>
            {
                var specName = string.Empty;
                var skuIds = spec.SpecNo.Split('-')
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Select(x => long.Parse(x))
                .ToList();
                skuIds.ForEach(id =>
                {
                    var sku = _itemSkuRepository.FirstOrDefault(id);
                    if (sku != null && sku.ItemSkuCategory != null)
                    {
                        specName = $"{specName}{sku.ItemSkuCategory.Name}:{sku.Sku};";
                    }
                });
                specName = specName.TrimEnd(';');
                spec.Spec = specName;
            });
        }

        public async Task<ItemSpecVO> GetItemSpecAsync(SingleId<long> form)
        {
            var spec = await _itemSpecRepository.FirstOrDefaultAsync(form.Id);
            return spec.ToVO<ItemSpec, ItemSpecVO>();
        }

   

        public async Task<ListResultDto<RecommendCategoryVO>> GetRecommendCategoriesAsync(HasStoreForm form)
        {
            var categories = _recommendCategoryRepository.GetAll().Where(x => x.StoreId == form.StoreId)
                .OrderBy(x => x.Sort);
            return await categories.ToListResultDtoAsync<RecommendCategory, RecommendCategoryVO>();
        }

        public async Task<RecommendCategoryVO> GetRecommendCategoryAsync(SingleId<long> form)
        {
            var category = await _recommendCategoryRepository.FirstOrDefaultAsync(form.Id);
            return category.ToVO<RecommendCategory, RecommendCategoryVO>();
        }

        public async Task MoveDownItemCategoryAsync(SingleId<long> form)
        {
            var category = await _itemCategoryRepository.FirstOrDefaultAsync(form.Id);
            var downCategory = _itemCategoryRepository.GetAll()
               // .Where(x => x.StoreId == category.StoreId && x.Sort > category.Sort)
               .Where(x => x.Sort > category.Sort)
                .OrderBy(x => x.Sort)
                .FirstOrDefault();
            if (downCategory != null)
            {
                var sort = downCategory.Sort;
                downCategory.Sort = category.Sort;
                category.Sort = sort;
            }
            else
            {
                category.Sort += 1;
            }
        }

        public async Task MoveDownItemAsync(SingleId<long> form)
        {
            var item = await _itemRepository.FirstOrDefaultAsync(form.Id);
            var downItem = _itemRepository.GetAll()
                .Where(x => x.StoreId == item.StoreId && x.Sort > item.Sort)
                .OrderBy(x => x.Sort)
                .FirstOrDefault();
            if (downItem != null)
            {
                var sort = downItem.Sort;
                downItem.Sort = item.Sort;
                item.Sort = sort;
            }
            else
            {
                item.Sort += 1;
            }
        }

        public async Task MoveDownRecommendCategoryAsync(SingleId<long> form)
        {
            var category = await _recommendCategoryRepository.FirstOrDefaultAsync(form.Id);
            var downCategory = _recommendCategoryRepository.GetAll()
                .Where(x => x.StoreId == category.StoreId && x.Sort > category.Sort)
                .OrderBy(x => x.Sort)
                .FirstOrDefault();
            if (downCategory != null)
            {
                var sort = downCategory.Sort;
                downCategory.Sort = category.Sort;
                category.Sort = sort;
            }
            else
            {
                category.Sort += 1;
            }
        }

        public async Task MoveUpItemCategoryAsync(SingleId<long> form)
        {
            var category = await _itemCategoryRepository.FirstOrDefaultAsync(form.Id);
            var upCategory = _itemCategoryRepository.GetAll()
                .Where(x => x.Sort < category.Sort)
                .OrderByDescending(x => x.Sort)
                .FirstOrDefault();
            if (upCategory != null)
            {
                var sort = upCategory.Sort;
                upCategory.Sort = category.Sort;
                category.Sort = sort;
            }
            else
            {
                category.Sort -= 1;
            }
        }

        public async Task MoveUpRecommendCategoryAsync(SingleId<long> form)
        {
            var category = await _recommendCategoryRepository.FirstOrDefaultAsync(form.Id);
            var upCategory = _recommendCategoryRepository.GetAll()
                .Where(x => x.StoreId == category.StoreId && x.Sort < category.Sort)
                .OrderByDescending(x => x.Sort)
                .FirstOrDefault();
            if (upCategory != null)
            {
                var sort = upCategory.Sort;
                upCategory.Sort = category.Sort;
                category.Sort = sort;
            }
            else
            {
                category.Sort -= 1;
            }
        }

        public async Task MoveUpItemAsync(SingleId<long> form)
        {
            var item = await _itemRepository.FirstOrDefaultAsync(form.Id);
            var upItem = _itemRepository.GetAll()
                .Where(x => x.StoreId == item.StoreId && x.Sort < item.Sort)
                .OrderByDescending(x => x.Sort)
                .FirstOrDefault();
            if (upItem != null)
            {
                var sort = upItem.Sort;
                upItem.Sort = item.Sort;
                item.Sort = sort;
            }
            else
            {
                item.Sort -= 1;
            }
        }

        public async Task RemoveItemAsync(SingleId<long> form)
        {
            await _itemRepository.DeleteAsync(form.Id);
        }

        public async Task RemoveItemCategoriesAsync(MultiplyId<long> form)
        {
            await _itemCategoryRepository.DeleteAsync(x => form.Ids.Contains(x.Id));
        }

        public async Task RemoveItemCommentAsync(SingleId<long> form)
        {
            await _itemCommentRepository.DeleteAsync(x => x.Id == form.Id);
        }

        public async Task RemoveItemSkuAsync(SingleId<long> form)
        {
            await _itemSkuRepository.DeleteAsync(form.Id);
        }

        public async Task RemoveItemSkuCategoryAsync(SingleId<long> form)
        {
            await _itemSkuCategoryRepository.DeleteAsync(form.Id);
        }

        [UnitOfWork(false)]
        public async Task RemoveItemSpecAsync(SingleId<long> form)
        {
            var itemSpec = await _itemSpecRepository.FirstOrDefaultAsync(form.Id);
            await _itemSpecRepository.DeleteAsync(itemSpec);
            CurrentUnitOfWork.SaveChanges();
            var item = await _itemRepository.FirstOrDefaultAsync(itemSpec.ItemId);
            ItemManager.ComputeItemPrice(item);
        }

        public async Task RemoveRecommendCategoryAsync(SingleId<long> form)
        {
            await _recommendCategoryRepository.DeleteAsync(x => x.Id == form.Id);
        }

        public async Task<ItemVO> SaveItemAsync(ItemForm form)
        {

            try {
                var id = form.Id;
                var store = await _storeRepository.FirstOrDefaultAsync(form.StoreId);
                if (store == null)
                {
                    throw new UserFriendlyException("店铺不存在");
                }
                var item = await _itemRepository.FirstOrDefaultAsync(id);
                var dividend = _dividendRepository.FirstOrDefault(x => x.Id == form.DividendId);
                if (item != null)
                {
                    item = form.MapTo(item);
                    item.ItemType = form.ItemType;
                    item.TreeTotalQty = form.TreeTotalQty ?? 0;
                    item.NumberPeriods = form.NumberPeriods ?? 0;
                    item.DividendId = form.DividendId;
                    if (dividend != null)
                    {
                        item.Timelimit = dividend.Timelimit;
                        item.DividendAmount = dividend.DividendAmount;
                        item.DividendTypes = dividend.DividendTypes;
                    }
                    else
                    {
                        item.Timelimit = 0;
                        item.DividendAmount = 0;
                        item.DividendTypes = 0;
                    }
                    item.IsGroup = form.IsGroup;
                    item.IsKeepPrice = store.IsKeepPrice;
                    item.GroupCount = form.IsGroup ? SingleUserMallConsts.GroupCount : 0;
                    item.IsTimeLimit = form.IsTimeLimit;
                    item.IsBargain = form.IsBargain;
                    ItemManager.ComputeItemPrice(item);
                    if (!item.IsTimeLimit)
                    {
                        item.LimitBeginTime = null;
                        item.LimitEndTime = null;
                        item.LimitPrice = 0;
                        var itemSpecs = _itemSpecRepository.GetAllList(x => x.ItemId == item.Id);
                        itemSpecs.ForEach(x => x.LimitPrice = 0);
                    }
                    if (!item.IsBargain)
                    {
                        item.BargainTimes = 0;
                        var itemSpecs = _itemSpecRepository.GetAllList(x => x.ItemId == item.Id);
                        itemSpecs.ForEach(x => x.BargainPrice = 0);
                    }
                    if(item.TreeTotalQty > 0)
                    {
                        item.TreeRemainingQty = item.TreeTotalQty - item.TotalSale;
                    }

                    if (item.TreeCount > 0)
                    {
                        item.LeftTreeCount = item.TreeCount - item.TotalSale;
                    }

                    await _itemRepository.UpdateAsync(item);
                }
                else
                {
                    item = form.MapTo<Item>();
                    item.ItemType = form.ItemType;
                    item.TreeTotalQty = form.TreeTotalQty ?? 0;
                    item.TreeRemainingQty = item.TreeTotalQty;
                    item.LeftTreeCount = item.TreeCount;
                    item.NumberPeriods = form.NumberPeriods ?? 0;
                    item.DividendId = form.DividendId;
                    if (dividend != null)
                    {
                        item.Timelimit = dividend.Timelimit;
                        item.DividendAmount = dividend.DividendAmount;
                        item.DividendTypes = dividend.DividendTypes;
                    }
                    else
                    {
                        item.Timelimit = 0;
                        item.DividendAmount = 0;
                        item.DividendTypes = 0;
                    }
                    item.IsGroup = form.IsGroup;
                    item.IsKeepPrice = store.IsKeepPrice;
                    item.GroupCount = form.IsGroup ? SingleUserMallConsts.GroupCount : 0;
                    item.IsTimeLimit = form.IsTimeLimit;
                    if (!item.IsTimeLimit)
                    {
                        item.LimitBeginTime = null;
                        item.LimitEndTime = null;
                        item.LimitPrice = 0;
                    }
                    if (!item.IsBargain)
                    {
                        item.BargainTimes = 0;
                        var itemSpecs = _itemSpecRepository.GetAllList(x => x.ItemId == item.Id);
                        itemSpecs.ForEach(x => x.BargainPrice = 0);
                    }
                    var lastItem = _itemRepository.GetAll()
                        .Where(x => x.StoreId == item.StoreId)
                        .OrderByDescending(x => x.Sort)
                        .FirstOrDefault();
                    if (lastItem != null)
                        item.Sort = lastItem.Sort + 1;
                    id = await _itemRepository.InsertAndGetIdAsync(item);
                }
                item = await _itemRepository.FirstOrDefaultAsync(id);
                return item.ToVO<Item, ItemVO>();
            }catch(Exception  ex)
            {
                throw ex;
            }
            }

        public async Task SaveItemCategoryAsync(ItemCategoryForm form)
        {
            var category = await _itemCategoryRepository.FirstOrDefaultAsync(form.Id);
            if (category != null)
            {
                category = form.MapTo(category);
                await _itemCategoryRepository.UpdateAsync(category);
            }
            else
            {
                category = form.MapTo<ItemCategory>();
                var lastCategory = _itemCategoryRepository.GetAll()
                   .Where(x => x.StoreId == category.StoreId)
                    .OrderByDescending(x => x.Sort)
                    .FirstOrDefault();
                if (lastCategory != null)
                    category.Sort = lastCategory.Sort + 1;
                await _itemCategoryRepository.InsertAsync(category);
            }
        }

        public async Task SaveItemSkuAsync(ItemSkuForm form)
        {
            var itemSku = await _itemSkuRepository.FirstOrDefaultAsync(form.Id);
            if (itemSku != null)
            {
                itemSku = form.MapTo(itemSku);
                await _itemSkuRepository.UpdateAsync(itemSku);
                RefreshSpecs(itemSku.ItemSkuCategory.ItemId);
            }
            else
            {
                itemSku = form.MapTo<ItemSku>();
                await _itemSkuRepository.InsertAsync(itemSku);
            }
        }

        public async Task SaveItemSkuCategoryAsync(ItemSkuCategoryForm form)
        {
            var itemSkuCategory = await _itemSkuCategoryRepository.FirstOrDefaultAsync(form.Id);
            if (itemSkuCategory != null)
            {
                itemSkuCategory = form.MapTo(itemSkuCategory);
                await _itemSkuCategoryRepository.UpdateAsync(itemSkuCategory);
                RefreshSpecs(itemSkuCategory.ItemId);
            }
            else
            {
                itemSkuCategory = form.MapTo<ItemSkuCategory>();
                await _itemSkuCategoryRepository.InsertAsync(itemSkuCategory);
            }
        }

        [UnitOfWork(false)]
        public async Task SaveItemSpecAsync(ItemSpecForm form)
        {
            var spec = await _itemSpecRepository.FirstOrDefaultAsync(form.Id);
            if (spec != null)
            {
                spec = form.MapTo(spec);
                await _itemSpecRepository.UpdateAsync(spec);
            }
            else
            {
                spec = form.MapTo<ItemSpec>();
                await _itemSpecRepository.InsertAsync(spec);
            }
            CurrentUnitOfWork.SaveChanges();
            var item = await _itemRepository.FirstOrDefaultAsync(form.ItemId);
            ItemManager.ComputeItemPrice(item);
        }

        public async Task SaveRecommendCategoryAsync(RecommendCategoryForm form)
        {
            var category = await _recommendCategoryRepository.FirstOrDefaultAsync(form.Id);
            if (category != null)
            {
                category = form.MapTo(category);
                await _recommendCategoryRepository.UpdateAsync(category);
            }
            else
            {
                category = form.MapTo<RecommendCategory>();
                var lastCategory = _recommendCategoryRepository.GetAll()
                    .Where(x => x.StoreId == category.StoreId)
                    .OrderByDescending(x => x.Sort)
                    .FirstOrDefault();
                if (lastCategory != null)
                    category.Sort = lastCategory.Sort + 1;
                await _recommendCategoryRepository.InsertAsync(category);
            }
        }

        public async Task SetItemSaleAsync(ItemSaleForm form)
        {
            var item = await _itemRepository.FirstOrDefaultAsync(form.Id);
            if (item != null)
            {
                item.IsSale = form.IsSale;
            }
        }
        /// <summary>
        /// 查询所有经营范围
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<BusinessScopeVO>> GetAllBusinessScopeAsync(BusinesssSearchForm form)
        {
            var query = _businessScopeRepository.GetAll()
                .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Name.Contains(form.Keywords))
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<BusinessScope, BusinessScopeVO>(form, (v, vo) => { });
        }
        /// <summary>
        /// 保存经营范围
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public async Task SaveBuusinessScopeAsync(BusinessScopeForm form)
        {
            var business = await _businessScopeRepository.FirstOrDefaultAsync(form.Id);
            if (business != null)
            {
                business = form.MapTo(business);
                await _businessScopeRepository.UpdateAsync(business);
            }
            else
            {
                business = form.MapTo<BusinessScope>();
                await _businessScopeRepository.InsertAsync(business);
            }
            CurrentUnitOfWork.SaveChanges();
        }

        public async Task<ListResultDto<ItemSpecVO>> GetItemSpecsAsync(SingleId<long> form)
        {
            var query = _itemSpecRepository.GetAll().Where(x => x.ItemId == form.Id)
            .OrderBy(x => x.Price);
            return await query.ToListResultDtoAsync<ItemSpec, ItemSpecVO>((i, vo) =>{});
        }
    }
}
